/* axios 跨域 2018-12-21 */

import Vue from 'vue'
import axios from 'axios'
import Router from '../router/index.js'
import Loading from '../util/loading.js'

/*
* 当请求头 headers: {'Content-Type': 'application/x-www-form-urlencoded'} 时，需要对post请求中的数据data进行序列化，使用querystring
* */
// import querystring from 'querystring'

const instance = axios.create({
  baseURL: 'http://localhost:3000',
  // baseURL: 'http://cp.tudingsoft.com/index.php/Api/',
  // withCredentials: true, // 是否携带 cookie，设置后需要后台配置对应的响应头
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
    // 'Content-Type': 'application/x-www-form-urlencoded'
  }
})

// 添加请求拦截器
instance.interceptors.request.use(
  config => {// 在发送请求之前做些什么
    /* 所有的请求携带 token */
    const token = localStorage.getItem('token')
    if (token) {
      Object.assign(config.headers, {'X-AUTH-TOKEN': token});
    }
    if (config.showLoading) {
      Loading.show()
    }
    return config
  },
  error => {
    // Loading.clear()
    Loading.networkError() // 显示网络错误
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  res => {
    Loading.clear()

    if (res.data.code == 404) {
      // 登录拦截
      Router.replace({
        path: '/main/login',
        query: {show_msg: true}
      })
    }

    return res
  },
  error => {
    // Loading.clear()
    return Promise.reject(error.response.data)
  }
)


/*
* get请求
* @param url
* @param data
* @param set
* @returns {Promise}
*/
export function apiGet(url, data = {}, set = {}) {
  if (set.timeout === undefined) set.timeout = 5000 // 设置响应时间
  if (set.showLoading === undefined) set.showLoading = true // 默认显示 loading
  if (set.showNetworkError === undefined) set.showNetworkError = true // 默认显示网络错误提示

  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: data,
      timeout: set.timeout,
      showLoading: set.showLoading,
      showNetworkError: set.showNetworkError
    }).then(response => {
      resolve(response)
    }).catch(error => {
      if (set.showNetworkError)
        Loading.networkError() // 显示网络错误
      else
        Loading.clear()
      reject(error)
    })
  })
}

/*
* post请求, 可以设置参数用来上传文件
* @param url
* @param data
* @param set
* @returns {Promise}
*/
export function apiPost(url, data = {}, set = {}) {
  if (set.timeout === undefined) set.timeout = 5000 // 设置响应时间
  if (set.showLoading === undefined) set.showLoading = true // 默认显示 loading
  if (set.showNetworkError === undefined) set.showNetworkError = true // 默认显示网络错误提示
  if (set.file === undefined) set.file = false // 默认为普通 post 请求, 不上传文件

  if (set.file) { // 上传文件
    set.headers = {'Content-Type': 'multipart/form-data'} // 上传文件的请求头
    let form = new FormData()
    for (var key in data) {
      form.append(key, data[key])
    }
    data = form
  } else {
    // data = querystring.stringify(data);
  }

  return new Promise((resolve, reject) => {
    instance.post(url, data, set).then(response => {
      resolve(response)
    }).catch(error => {
      if (set.showNetworkError)
        Loading.networkError() // 显示网络错误
      else
        Loading.clear()
      reject(error)
    })
  })
}

Vue.apiGet = apiGet
Vue.apiPost = apiPost
Vue.prototype.apiGet = apiGet
Vue.prototype.apiPost = apiPost
